// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  // 取出两个数组的相同元素
  getArrEqual(arr1, arr2) {
    const newArr = [];
    for (let i = 0; i < arr2.length; i++) {
      for (let j = 0; j < arr1.length; j++) {
        if (arr1[j] === arr2[i]) {
          newArr.push(arr1[j]);
        }
      }
    }
    return newArr;
  }
  // 取出两个数组的不同元素
  getArrDifference(arr1, arr2) {
    return arr1.concat(arr2).filter(function(v, i, arr) {
      return arr.indexOf(v) === arr.lastIndexOf(v);
    });
  }

  async subjectlistAction() {
    const page = this.post();
    const pages = page.pages;
    const limits = page.limits;
    const search = page.search;
    const zt = page.zt;
    const shopid = this.shop_userinfo.departmentid;

    const data = await this.model('or_subject_config')
      .alias('scf')
      .field('scf.subjectid, ss.isdisable, s.name, s.number, sc.name as cname, b.name as bname, s.remarks, ss.usetime, ss.price')
      .join('think_or_subject s on s.id=scf.subjectid')
      .join('think_or_shop_subject ss on ss.subjectid=scf.subjectid')
      .join('think_or_brand b on b.id=s.brandid')
      .join('think_or_subjectcategory sc on sc.id=s.categoryid')
      .where({ 'scf.departmentid': shopid, 'ss.isdisable': zt, 'scf.type': 2, 's.name|s.number': ['like', '%' + search + '%'] })
      .group('scf.subjectid')
      .page(pages, limits)
      .order('scf.id DESC')
      .countSelect();

    return this.json(data);
  }

  // pull organization subjects to shop
  async pullsubjectsAction() {
    let flag = true;
    const or_subsid = JSON.parse(this.post('data'));
    const shopid = this.shop_userinfo.departmentid;
    const orid = await this.model('or_department').where({ id: shopid }).getField('pid', true);
    // check pull subjects whether repeat in shop.
    const pulled_subs = await this.model('or_shop_subject').where({ shopid: shopid }).getField('subjectid');
    const pulled_subs2 = await this.model('or_subject_config').where({ departmentid: shopid, type: 2 }).group('subjectid').getField('subjectid');

    this.getArrEqual(pulled_subs, pulled_subs2).forEach((v) => {
      if (or_subsid.indexOf(v) !== -1) {
        flag = false;
        return this.fail('拉取的项目已经存在');
      }
    });

    if (flag) {
      const add_data = [];
      const add_data2 = [];

      const or_subsid2 = await this.model('or_shop_subject').where({ shopid: shopid, subjectid: ['IN', or_subsid] }).getField('subjectid');
      const or_subsid3 = this.getArrDifference(or_subsid, or_subsid2);

      const or_sub_list = await this.model('or_subject_config').where({ type: 2, departmentid: orid, subjectid: ['IN', or_subsid] }).select();
      or_sub_list.forEach((v) => {
        add_data.push({
          subjectid: v.subjectid,
          subjectchildclassid: v.subjectchildclassid,
          type: 2,
          departmentid: shopid,
          // xjyjtype: v.xjyjtype,
          xjyjpercent: v.xjyjpercent,
          // xjyjfixed: v.xjyjfixed,
          xjtctype: v.xjtctype,
          xjtcpercent: v.xjtcpercent,
          xjtcfixed: v.xjtcfixed,
          // khyjtype: v.khyjtype,
          khyjpercent: v.khyjpercent,
          // khyjfixed: v.khyjfixed,
          khtctype: v.khtctype,
          khtcpercent: v.khtcpercent,
          khtcfixed: v.khtcfixed
          // minuscost: v.minuscost
        });
      });
      if (or_subsid3.length !== 0) {
        const or_sub_list2 = await this.model('or_subject').where({ departmentid: orid, id: ['IN', or_subsid3] }).select();
        or_sub_list2.forEach((v) => {
          add_data2.push({
            subjectid: v.id,
            shopid: shopid,
            price: v.price,
            usetime: v.usetime
          });
        });
      }

      const model = this.model('or_shop_subject');
      if (add_data.length !== 0) {
        if (add_data2.length !== 0) {
          await model.transaction(async() => {
            try {
              const res1 = await model.addMany(add_data2);
              const res2 = await this.model('or_subject_config').db(model.db()).addMany(add_data);
              if (res1 && res2) {
                await model.commit();
                return this.success('拉取成功!');
              } else {
                await model.rollback();
                return this.fail('拉取失败');
              }
            } catch (e) {
              await model.rollback();
              return this.fail('拉取失败！');
            }
          });
        } else {
          await model.transaction(async() => {
            try {
              const res = await this.model('or_subject_config').db(model.db()).addMany(add_data);
              if (res) {
                await model.commit();
                return this.success('拉取成功!');
              } else {
                await model.rollback();
                return this.fail('拉取失败');
              }
            } catch (e) {
              await model.rollback();
              return this.fail('拉取失败！');
            }
          });
        }
      } else {
        return this.fail('请先配置好机构项目的业绩和提成信息!');
      }
    }
  }

  // 编辑项目
  async editsubjectAction() {
    let flag = true;

    const subInfo = this.post().subInfo;
    const subConfig = this.post().subConfig;
    const shopid = this.shop_userinfo.departmentid;

    const insertsub = [];
    const updatesub = [];
    const reducesub = [];
    const subconfclassidlists = [];

    const getFieldata = await this.model('or_subject_config').where({ subjectid: subInfo.id, type: 2, departmentid: shopid }).getField('subjectchildclassid,id');
    const subconflists = getFieldata.subjectchildclassid;
    const subconfidlists = getFieldata.id;
    subConfig.forEach((v) => {
      subconfclassidlists.push(v.subjectchildclassid);
    });
    subConfig.forEach((v) => {
      if (subconflists.includes(v.subjectchildclassid)) {
        delete (v['name']);
        v['id'] = subconfidlists[subconflists.indexOf(v.subjectchildclassid)];
        updatesub.push(v);
      } else {
        insertsub.push({
          subjectid: subInfo.id,
          subjectchildclassid: v.subjectchildclassid,
          type: 2,
          departmentid: shopid,
          // xjyjtype: v.xjyjtype,
          xjyjpercent: v.xjyjpercent,
          // xjyjfixed: v.xjyjfixed,
          xjtctype: v.xjtctype,
          xjtcpercent: v.xjtcpercent,
          xjtcfixed: v.xjtcfixed,
          // khyjtype: v.khyjtype,
          khyjpercent: v.khyjpercent,
          // khyjfixed: v.khyjfixed,
          khtctype: v.khtctype,
          khtcpercent: v.khtcpercent,
          khtcfixed: v.khtcfixed
          // minuscost: v.minuscost
        });
      }
    });
    subconflists.forEach((v) => {
      if (!subconfclassidlists.includes(v)) {
        reducesub.push(v);
      }
    });

    const model = this.model('or_subject_config');
    await model.transaction(async() => {
      try {
        const upsubIfnum = await this.model('or_shop_subject').db(model.db()).where({ subjectid: subInfo.id }).update({ price: subInfo.price, usetime: subInfo.usetime });
        if (insertsub.length !== 0) {
          const return1 = await model.addMany(insertsub);
          if (!return1) { flag = false };
        }
        if (updatesub.length !== 0) {
          const return2 = await model.updateMany(updatesub);
          if (!return2) { flag = false };
        }
        if (reducesub.length !== 0) {
          const return3 = await model.where({ subjectid: subInfo.id, subjectchildclassid: ['in', reducesub], type: 2, departmentid: shopid }).delete();
          if (!return3) { flag = false };
        }
        if (upsubIfnum && flag) {
          await model.commit();
          return this.success('更新成功!');
        } else {
          await model.rollback();
          return this.fail('更新失败!');
        }
      } catch (e) {
        await model.rollback();
        return this.fail('更新失败!');
      }
    });

    // let data = {
    // 	price: subInfo.price,
    // 	usetime: subInfo.usetime,
    // xstdtype: sinfo.xstdtype,
    // xspercent: Number(sinfo.xspercent/100).toFixed(2),
    // xsfixed: sinfo.xsfixed,
    // sgtdtype: sinfo.sgtdtype,
    // sgpercent: Number(sinfo.sgpercent/100).toFixed(2),
    // sgfixed: sinfo.sgfixed,
    // khtdtype: sinfo.khtdtype,
    // khpercent: Number(sinfo.khpercent/100).toFixed(2),
    // khfixed: sinfo.khfixed
    // }

    // let res = await this.model('or_shop_subject').where({id: sinfo.id}).update(data);

    // return res?this.success('更改成功'):this.fail('更改失败');
  }

  // 项目启用和停用
  async unstopAction() {
    const id = this.post('id');
    const status = this.post('status');
    const shopid = this.shop_userinfo.departmentid;

    const res = await this.model('or_shop_subject').where({ subjectid: id, shopid: shopid }).update({ isdisable: status });

    if (status * 1) {
      return res ? this.success('停用成功') : this.fail('停用失败');
    } else {
      return res ? this.success('启用成功') : this.fail('启用失败');
    }
  }

  // 获取机构项目二级分类
  async getorsubjectcategoryAction() {
    const shopid = this.shop_userinfo.departmentid;

    const orid = await this.model('or_department').where({ id: shopid }).getField('pid', true);

    // let data = await this.model('or_subjectcategory').where({departmentid: orid, pid: ['>', 0]}).select();

    const data = await this.model().query('select a.id,CONCAT_WS(" ---> ",a.name,b.name) as name FROM `think_or_subjectcategory` AS a LEFT JOIN `think_or_subjectcategory` AS b ON a.pid = b.id WHERE a.departmentid=' + orid + ' AND a.pid > 0');

    return this.json(data);
  }

  // 获取机构分类下的项目
  async querysubjectsAction() {
    let cateids = JSON.parse(this.post('cates'));

    if (think.isEmpty(cateids)) cateids = [0];

    const shopid = this.shop_userinfo.departmentid;

    const orid = await this.model('or_department').where({ id: shopid }).getField('pid', true);

    const subjectlist = await this.model('or_subject').where({ departmentid: orid, categoryid: ['IN', cateids], isdisable: 0 }).select();

    const existid = await this.model('or_subject_config').where({ departmentid: shopid, type: 2 }).group('subjectid').getField('subjectid');
    const existid2 = await this.model('or_shop_subject').where({ shopid: shopid }).getField('subjectid');

    const data = {
      subjects: subjectlist,
      existsub: this.getArrEqual(existid, existid2)
    };

    return this.json(data);
  }

  async getsubjectconfigAction() {
    const subjectid = this.post().subjectid;
    const shopid = this.shop_userinfo.departmentid;
    const data = await this.model('or_subject_config')
      .alias('sc')
      .field('sc.*,sl.name')
      .join('`think_or_subject_childclass` sl on sc.subjectchildclassid=sl.id')
      .where({ 'sc.subjectid': subjectid, 'sc.departmentid': shopid, 'sc.type': 2 })
      .select();

    return this.json(data);
  }

  async getSubjectChildClassAction() {
    const shopid = this.shop_userinfo.departmentid;
    const orid = await this.model('or_department').where({ id: shopid }).getField('pid', true);
    const info = await this.model('or_subject_childclass').where({ departmentid: orid, type: 2 }).select();
    return this.json(info);
  }
}
